package com.lx.base.registrsar;

import com.lx.base.api.dto.BaseDto;
import com.lx.base.exception.BizException;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


@ControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseDto<String> errorHandler(HttpServletRequest req, Exception e) throws Exception {

        log.error("系统异常：", e);
        return BaseDto.fail("","系统异常");
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseDto<String> validHandler(HttpServletRequest req, MethodArgumentNotValidException e) throws Exception {

        log.error("参数错误：", e);
        return BaseDto.fail("",e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public BaseDto<String> bizExceptionHandler(HttpServletRequest req, BizException e) throws Exception {

        log.error("业务数据异常：", e);
        return BaseDto.fail(e.getCodeMessage());
    }

    //jackson反序列化失败引起的异常
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public BaseDto<String> mismatchedHandler(HttpServletRequest req, MismatchedInputException e) throws Exception {

        log.error("参数格式错误：", e);
        return BaseDto.fail("","参数格式错误:" + e.getMessage());
    }
}
